package com.meet.bizservice.impl;

import com.meet.persist.dao.UserDao;
import com.meet.api.dto.response.MeetInterestTagListResponseDTO;
import com.meet.api.dto.response.MeetUserLoginResponseDTO;
import com.meet.api.dto.response.MeetUserProfileResponseDTO;
import com.meet.api.dto.response.MeetUserResponseDTO;
import com.meet.persist.entity.User;
import com.meet.exception.BusinessException;
import com.meet.bizservice.UserBizService;
import com.meet.util.JwtUtil;
import com.meet.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class UserBizServiceImpl implements UserBizService {

    private static final Logger logger = LoggerFactory.getLogger(UserBizServiceImpl.class);

    @Resource
    private UserDao userDao;

    // JwtUtil是工具类，不需要注入

    @Override
    public Result<MeetUserResponseDTO> register(String username, String password, String phone, String email) {

        try {
            logger.info("Starting user registration for username: {}", username);

            // 检查用户名、手机号和邮箱是否已存在
            if (userDao.findByUsername(username) != null) {
                logger.warn("Registration failed - username already exists: {}", username);
                return Result.error(400, "用户名已存在");
            }

            if (phone != null && !phone.isEmpty() && userDao.findByPhone(phone) != null) {
                logger.warn("Registration failed - phone already exists: {}", phone);
                return Result.error(400, "手机号已存在");
            }

            if (email != null && !email.isEmpty() && userDao.findByEmail(email) != null) {
                logger.warn("Registration failed - email already exists: {}", email);
                return Result.error(400, "邮箱已存在");
            }

            // 创建新用户
            User user = new User();
            user.setUserId(UUID.randomUUID().toString().replace("-", ""));
            user.setUsername(username);
            user.setPasswordHash(password); // 实际项目中需要加密
            user.setPhone(phone);
            user.setEmail(email);
            user.setStatus(1); // 启用状态

            if (userDao.insert(user)) {
                logger.info("User registered successfully with ID: {}", user.getUserId());

                // 生成JWT token
                String token = JwtUtil.generateToken(username, user.getUserId());

                // 返回包含token的用户信息
                user.setPasswordHash(null); // 不返回密码哈希值

                MeetUserResponseDTO userDTO = convertToResponseDTO(user);
                userDTO.setToken(token); // 添加token到返回数据

                return Result.success(userDTO);
            } else {
                logger.error("Failed to insert user into database");
                throw new BusinessException("注册失败");
            }
        } catch (Exception e) {
            logger.error("Error during user registration", e);
            throw new BusinessException("注册过程中发生错误");
        }
    }

    @Override
    public Result<MeetUserLoginResponseDTO> login(String username, String password) {

        logger.info("Starting user login for username: {}", username);

        User user = userDao.findByUsername(username);

        if (user == null) {
            logger.warn("Login failed - user not found: {}", username);
            return Result.error(401, "用户名或密码错误");
        }

        if (!user.getPasswordHash().equals(password)) {
            logger.warn("Login failed - invalid password for user: {}", username);
            return Result.error(401, "用户名或密码错误");
        }

        // 更新最后活跃时间
        user.setLastActiveTime(new java.util.Date());
        userDao.update(user);

        logger.info("User logged in successfully: {}", username);

        // 生成JWT token
        String token = JwtUtil.generateToken(username, user.getUserId());

        // 返回用户信息和token
        user.setPasswordHash(null); // 不返回密码哈希值

        MeetUserResponseDTO userDTO = convertToResponseDTO(user);
        userDTO.setToken(token); // 添加token到返回数据

        // 创建登录响应对象
        MeetUserProfileResponseDTO profileDTO = new MeetUserProfileResponseDTO();
        profileDTO.setUserId(userDTO.getUserId());
        profileDTO.setUsername(userDTO.getUsername());
        profileDTO.setNickname(userDTO.getNickname());
        profileDTO.setAvatarUrl(userDTO.getAvatarUrl());
        // 注意：这里不包含interestTags，因为UserProfileResponseDTO结构简单

        MeetUserLoginResponseDTO loginResponse = new MeetUserLoginResponseDTO();
        loginResponse.setToken(token);
        loginResponse.setUser(profileDTO);

        return Result.success(loginResponse);
    }

    @Override
    public Result<MeetUserResponseDTO> getProfile() {

        try {
            logger.info("Getting user profile");

            // 这里应该从JWT中获取用户ID，为简化演示直接返回示例数据
            User user = new User();
            user.setUserId("1234567890");
            user.setUsername("testuser");
            user.setNickname("测试用户");
            user.setAvatarUrl("https://example.com/avatar.jpg");
            user.setPhone("13800138000");
            user.setEmail("test@example.com");
            user.setMemberLevel("premium");

            MeetUserResponseDTO userDTO = convertToResponseDTO(user);
            return Result.success(userDTO);
        } catch (Exception e) {
            logger.error("Error getting user profile", e);
            throw new BusinessException("获取用户资料失败");
        }
    }

    @Override
    public Result<MeetUserResponseDTO> updateProfile(String nickname, String avatarUrl, List<String> interestTags) {

        try {
            logger.info("Updating user profile");

            // 这里应该从JWT中获取用户ID，为简化演示直接返回示例数据
            User user = new User();
            user.setUserId("1234567890");
            user.setNickname(nickname);
            user.setAvatarUrl(avatarUrl);

            MeetUserResponseDTO userDTO = convertToResponseDTO(user);
            return Result.success(userDTO);
        } catch (Exception e) {
            logger.error("Error updating user profile", e);
            throw new BusinessException("更新用户资料失败");
        }
    }

    @Override
    public Result<MeetInterestTagListResponseDTO> getInterestTags() {

        try {
            logger.info("Getting user interest tags");

            // 这里应该从JWT中获取用户ID，为简化演示直接返回示例数据
            return Result.success(new MeetInterestTagListResponseDTO(Arrays.asList("音乐", "电影", "旅游")));
        } catch (Exception e) {
            logger.error("Error getting interest tags", e);
            throw new BusinessException("获取兴趣标签失败");
        }
    }

    @Override
    public Result<Boolean> updateInterestTags(List<String> interestTags) {

        try {
            logger.info("Updating user interest tags");

            // 这里应该从JWT中获取用户ID，为简化演示直接返回成功
            return Result.success(true);
        } catch (Exception e) {
            logger.error("Error updating interest tags", e);
            throw new BusinessException("更新兴趣标签失败");
        }
    }

    private MeetUserResponseDTO convertToResponseDTO(User user) {

        if (user == null) {
            return null;
        }

        MeetUserResponseDTO dto = new MeetUserResponseDTO();
        dto.setUserId(user.getUserId());
        dto.setUsername(user.getUsername());
        dto.setNickname(user.getNickname());
        dto.setAvatarUrl(user.getAvatarUrl());
        dto.setPhone(user.getPhone());
        dto.setEmail(user.getEmail());
        dto.setMemberLevel(user.getMemberLevel());
        dto.setJoinDate(user.getJoinDate());
        dto.setLastActiveTime(user.getLastActiveTime());
        dto.setStatus(user.getStatus());
        dto.setCreatedAt(user.getCreatedAt());
        dto.setUpdatedAt(user.getUpdatedAt());

        return dto;
    }

}
